package edu.ccut.saturn.manager.bundles.core;

import java.io.File;
import java.io.IOException;
import java.util.List;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.IValidateInfo;
import edu.ccut.saturn.component.IValidateUseInfo;
import edu.ccut.saturn.component.SaturnDataManager;
import edu.ccut.saturn.component.xml.XMLHelper;
import edu.ccut.saturn.manager.bundles.core.Activator;


public class DeleteDataItemValidate extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		
		String fullKey = (String) parameterContext.getParameterValue(0);
		String dataItemName = (String) parameterContext.getParameterValue(1);
		String validateInfoFullkey = (String) parameterContext
				.getParameterValue(2);
		
		IDataInfo dataInfo = SaturnDataManager.getInstance().getSaturnDataInfo(fullKey);
		IDataItem dataItem = dataInfo.getDataItem(dataItemName);
		IValidateUseInfo validateUseInfo = dataItem.getValidateUseInfo();
		List<IValidateInfo> validateInfos  = null;
		
		if(validateUseInfo != null){
			validateInfos = validateUseInfo.getValidateInfos();
		}
		
		for(IValidateInfo validateInfo : validateInfos){
			if(validateInfo.getValidateInfoFullkey().equals(validateInfoFullkey)){
				validateInfos.remove(validateInfo);
				break;
			}
		}
		
		this.createSaturnDataPachFileByDataInfo(fullKey, dataInfo);
	}
	
	private void createSaturnDataPachFileByDataInfo(String fullKey, IDataInfo dataInfo) throws IOException {

		// 将componentInfo生成文件
		String dir = Activator.getServerLocation() + File.separator + "patch"
				+ File.separator;
		// "c:" + File.separator + "patch" + File.separator;
		String[] fullKeyItem = fullKey.split("::");
		String directPath = (fullKeyItem[0].substring(7, fullKeyItem[0]
				.length())).replaceAll("/", File.separator + File.separator);

		String directPathTransformed = dir + directPath + File.separator;

		String componentFileDir = null;
		if (dataInfo.getSqlStr() != null && !"".equals(dataInfo.getSqlStr())) {
			componentFileDir = fullKeyItem[1] + ".sqldata";
		} else {
			componentFileDir = fullKeyItem[1] + ".saturndata";
		}
		XMLHelper.writeFile(directPathTransformed, componentFileDir, dataInfo
				.toXmlStr());
	}
}